package com.rzt.cft.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzt.cft.constant.StatusConstant;
import com.rzt.cft.constant.TypeConstant;
import com.rzt.cft.entity.project.ProjectDetail;
import com.rzt.cft.entity.project.ProjectOrder;
import com.rzt.cft.service.project.IProjectDetailService;
import com.rzt.cft.service.project.IProjectOrderService;
import com.rzt.cft.service.uc.IUcRebateLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 *  定时任务类
 * @author 钟忠
 * @date 2020/3/7 14:44
 */
@Slf4j
@Component
public class TimeController {

    @Autowired
    private IProjectOrderService projectOrderService;

    @Autowired
    private IProjectDetailService projectDetailService;

    @Autowired
    private IUcRebateLogService ucRebateLogService;

    /**
     * 每天凌晨执行智能返利
     */
    @Scheduled(cron = "1 0 0 * * ?")
    public void intelligenceRebate() {
        log.info("每天凌晨执行智能返利 定时执行 。。。。。............... : {}" , LocalDateTime.now());
        //查询当天还在进行中的智能项目订单
        QueryWrapper<ProjectOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", StatusConstant.ProjectOrderStatus.IN_HAND);
        queryWrapper.eq("project_type", TypeConstant.projectType.INTELLIGENCE);
        List<ProjectOrder> projectOrderList = projectOrderService.list(queryWrapper);
        projectOrderList.forEach(x -> {
            ucRebateLogService.intelligenceRebate(x);
        });
    }

    /**
     * 每个小时执行一次自选返利
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void optionalRebate() {
        log.info("每个小时执行一次自选返利 定时执行 。。。。。............... : {}" , LocalDateTime.now());
        //查询当天还在进行中的智能项目订单
        QueryWrapper<ProjectOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", StatusConstant.ProjectOrderStatus.IN_HAND);
        queryWrapper.eq("project_type", TypeConstant.projectType.OPTIONAL);
        queryWrapper.le("completion_time", LocalDateTime.now());
        List<ProjectOrder> projectOrderList = projectOrderService.list(queryWrapper);
        projectOrderList.forEach(x -> {
            ucRebateLogService.optionalRebate(x);
        });
    }

    /**
     * 每分钟执行一次查看项目是否结束
     */
    @Scheduled(cron = "0 * * * * ?")
    public void endProject() {
        //查询当天还在进行中的智能项目订单
        QueryWrapper<ProjectDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", StatusConstant.ProjectStatus.IN_HAND);
        queryWrapper.le("end_time", LocalDateTime.now());
        List<ProjectDetail> projectDetails = projectDetailService.list(queryWrapper);
        projectDetails.forEach(x -> {
            x.setStatus(StatusConstant.ProjectStatus.QUIT);
            projectDetailService.updateById(x);
        });
    }

}
